<!-- 商品发布 - 库存价格 - 属性列表 -->
<template>
  <el-col v-for="(item, index) in attributeList" :key="index">
    <div>
      <el-text class="mx-1">属性名：</el-text>
      <el-tag class="mx-1" :closable="!isDetail" type="success" @close="handleCloseProperty(index)">
        {{ item.name }}
      </el-tag>
    </div>
    <div>
      <table class="attribute-table">
        <tr>
          <td>显示用的属性值</td>
          <td width="100px;" :key="value.name" v-for="(value, valueIndex) in item.values">
            <el-icon v-if="!isDetail" @click="handleCloseValue(index, valueIndex, item.id, value.name)" style="position:absolute;right:0px;top:0px;color:#000;font-size:20px;" class="close-btn"><CircleClose /></el-icon>
            <input @blur="updateAttributeNameValue(value, item.id)" v-if="!isDetail" type="text" style="width:100px;" v-model="value.name" />
            <span v-else>{{value.name}}</span>
          </td>
          <td v-if="!isDetail">
            <input
placeholder="输入显示属性值" type="text" style="width:100px;"
               v-model="item.inputValue" @blur="handleInputConfirm(index, item.id, item)"
               @keyup.enter="handleInputConfirm(index, item.id, item)"
            />
          </td>
        </tr>
        <tr>
          <td>结构化的属性值</td>
          <td :key="value.name" v-for="(value) in item.values">
            <!--为了让input强制刷新，放到这里，无实际用途-->
            <span style="display:none;">{{value}}</span>
            <input @blur="updateAttributeStructuredValue(value, item.id)" v-if="!isDetail" type="text" style="width:100px;" v-model="value.structuredValue" />
            <span v-show="isDetail">{{value.structuredValue}}</span>
          </td>
        </tr>
      </table>
<!--      <el-text class="mx-1">显示用的属性值：</el-text>-->
<!--      <el-tag-->
<!--        v-for="(value, valueIndex) in item.values"-->
<!--        :key="value.name"-->
<!--        class="mx-1"-->
<!--        :closable="!isDetail"-->
<!--        @close="handleCloseValue(index, valueIndex)"-->
<!--      >-->
<!--        {{ value.name }}-->
<!--      </el-tag>-->
<!--      <el-input-->
<!--        v-show="inputVisible(index)"-->
<!--        :id="`input${index}`"-->
<!--        :ref="setInputRef"-->
<!--        v-model="inputValue"-->
<!--        class="!w-20"-->
<!--        size="small"-->
<!--        @blur="handleInputConfirm(index, item.id)"-->
<!--        @keyup.enter="handleInputConfirm(index, item.id)"-->
<!--      />-->
<!--      (用,分割对应结构化的属性值)-->
<!--      <el-button-->
<!--        v-show="!inputVisible(index)"-->
<!--        class="button-new-tag ml-1"-->
<!--        size="small"-->
<!--        @click="showInput(index)"-->
<!--      >-->
<!--        + 添加-->
<!--      </el-button>-->
    </div>
    <el-divider class="my-10px" />
  </el-col>
</template>

<script lang="ts" setup>
import { ElInput } from 'element-plus'
import * as PropertyApi from '@/api/mall/product/property'
import { PropertyVO } from '@/api/mall/product/property'
import { PropertyAndValues } from '@/views/mall/product/spu/components'
import { propTypes } from '@/utils/propTypes'

defineOptions({ name: 'ProductAttributes' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const inputValue = ref('') // 输入框值
const attributeIndex = ref<number | null>(null) // 获取焦点时记录当前属性项的index
// 输入框显隐控制
const inputVisible = computed(() => (index: number) => {
  if (attributeIndex.value === null) return false
  if (attributeIndex.value === index) return true
})
const inputRef = ref([]) //标签输入框Ref
/** 解决 ref 在 v-for 中的获取问题*/
const setInputRef = (el) => {
  if (el === null || typeof el === 'undefined') return
  // 如果不存在 id 相同的元素才添加
  if (!inputRef.value.some((item) => item.input?.attributes.id === el.input?.attributes.id)) {
    inputRef.value.push(el)
  }
}
const attributeList = ref<PropertyAndValues[]>([]) // 商品属性列表
const props = defineProps({
  propertyList: {
    type: Array,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

watch(
  () => props.propertyList,
  (data, oldValue) => {
    if (!data) return

    attributeList.value = data.map(item=> {
      let newValues = item.values.map(e=> {
        e.oriName = e.name;

        return {
          ...e
        }
      });

      return {
        ...item,
        values: newValues,
        inputValue: ""
      };
    });
  },
  {
    deep: true,
    immediate: true
  }
)

/** 删除属性值*/
const handleCloseValue = (index: number, valueIndex: number, propertyId, valueName) => {
  attributeList.value[index].values?.splice(valueIndex, 1)
  emit("updatePropertyList", attributeList.value);
  emit("removeAttribute", propertyId, valueName);
}

/** 删除属性*/
const handleCloseProperty = (index: number) => {
  attributeList.value?.splice(index, 1)
  emit("updatePropertyList", attributeList.value);
}

/** 显示输入框并获取焦点 */
const showInput = async (index) => {
  attributeIndex.value = index
  inputRef.value[index].focus()
}

/** 输入框失去焦点或点击回车时触发 */
const emit = defineEmits(['success', "updateAttributeStructuredValue", "updateAttributeNameValue", "removeAttribute", "updatePropertyList"]) // 定义 success 事件，用于操作成功后的回调

const updateAttributeStructuredValue = (attribute, propertyId)=> {
  emit("updateAttributeStructuredValue", attribute, propertyId)
}

const updateAttributeNameValue = (attribute, propertyId)=> {
  let structuredValue: any = parseInt(attribute.name);
  if(isNaN(structuredValue)) {
    structuredValue = attribute.name;
  }
  attribute.structuredValue = structuredValue;
  emit("updateAttributeNameValue", attribute, propertyId);
  // 等sku更新完之后，更新oriName
  setTimeout(()=> {
    attribute.oriName = attribute.name;
    emit("updateAttributeStructuredValue", attribute, propertyId)
  }, 50);
}

const handleInputConfirm = async (index: number, propertyId: number, item) => {
  let value = item.inputValue;
  let structuredValue: any;
  let name = value;
  // if(value.includes(",")) {
  //   name = value.split(",")[0];
  //   structuredValue = value.split(",")[0];
  // }
  if (value) {
    // 判断属性是否重复
    let existValue = attributeList.value[index].values?.find(e=>e.name === name);
    if(existValue) {
      message.error("存在重复的属性名");
      return;
    }

    structuredValue = parseInt(value);
    if(isNaN(structuredValue)) {
      structuredValue = value;
    }
    // 保存属性值
    try {
      // const id = await PropertyApi.createPropertyValue({ propertyId, name, structValue })
      attributeList.value[index].values.push({id: +new Date(), name, structuredValue, oriName: name })
      message.success(t('common.createSuccess'))
      emit('success', attributeList.value)
      item.inputValue = "";
    } catch {
      message.error('添加失败，请重试')
    }
  }
  attributeIndex.value = null
  // inputValue.value = ''
}
</script>

<style lang="scss" scoped>
.attribute-table {
  border-collapse: collapse;
  td,th {
    padding: 0px 16px;
    border: 1px solid black;
    position: relative;
    input {
      padding: 0px;
      outline: none;
      height: 35px;
      display: block;
      border: none;
    }
  }
}
</style>
